﻿#include "mainwindow.h"
#include "ui_mainwindow.h"


MainWindow::MainWindow(QWidget *parent) :
	QMainWindow(parent),
	ui(new Ui::MainWindow) {
	relQRImage = nullptr;
	ui->setupUi(this);
}

MainWindow::~MainWindow() {
	delete ui;
}
#include "QDebug"
void MainWindow::on_pushButton_clicked() {
	QRecLevel ecl = QRecLevel(ui->ecLevel->value());
	QString txt = ui->text->toPlainText();
	txt = txt.trimmed();

	if (txt.isEmpty()) {
		return;
	}

	if (relQRImage != nullptr) {
		delete this->relQRImage;
	}

	QRcode* qrcode = QRcode_encodeString(txt.toStdString().data(), 1, ecl, QR_MODE_8, 1);
	this->relQRImage = drawQRCode(qrcode);
	this->ui->view->setPixmap(this->relQRImage->scaled(250, 250, Qt::KeepAspectRatio));
}

using namespace std;
QPixmap* MainWindow::drawQRCode(QRcode *qrcode) {
	int w = qrcode->width;
	QPixmap *map = new QPixmap(w * w, w * w);
	QPainter painter(map);
	map->fill(QColor(255, 255, 255));
	// ui->view->activateWindow();
	// 反走样
	// painter.setRenderHint(QPainter::Antialiasing, true);
	// 设置画笔颜色、宽度
	//painter.setPen(QPen(QColor(0, 160, 230), 5));
	// 设置画刷颜色
	QColor h(0, 0, 0);

	if (qrcode == nullptr) {
		return map;
	}

	for (int i = 0; i < w; i++) {
		for (int j = 0; j < w; j++) {
			unsigned char d = qrcode->data[i * w + j];

			if (d & 0x01) {
				painter.setBrush(h);
				painter.drawRect(i * w, j * w, w, w);
			}
		}
	}

	return map;
}
